﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace CharacterCreation.Web.Models {
    public class Repository<TEntity> : IDisposable where TEntity : BaseModel {
        CharacterContext context = new CharacterContext();

        public void Add(TEntity entity) {
            context.Set<TEntity>().Add(entity);
            context.SaveChanges();
        }

        public IEnumerable<TEntity> GetAll(Expression<Func<TEntity, bool>> where = null) {
            if (where != null)
                return context.Set<TEntity>().Where(where);
            else
                return context.Set<TEntity>();
        }

        public TEntity Get(Guid id) {
            return context.Set<TEntity>().Find(id);
        }

        public void Delete(TEntity entity) {
            context.Set<TEntity>().Remove(entity);
            context.SaveChanges();
        }

        public void Delete(Guid id) {
            Delete(Get(id));
        }

        public void Update(TEntity entity) {
            context.Set<TEntity>().Attach(entity);
            context.Entry(entity).State = System.Data.EntityState.Modified;
            context.SaveChanges();
        }

        public void Dispose() {
        }

    }
}